package net.zoneland.zrdp.common.utils.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Objects;

import net.zoneland.zrdp.common.utils.DateUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import net.zoneland.zrdp.common.config.ZonevueConfig;
import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.exception.UtilException;
import net.zoneland.zrdp.common.exception.file.FileNameLengthLimitExceededException;
import net.zoneland.zrdp.common.exception.file.FileSizeLimitExceededException;
import net.zoneland.zrdp.common.exception.file.InvalidExtensionException;
import net.zoneland.zrdp.common.utils.uuid.Seq;

/**
 * 文件上传工具类
 *
 * @author zonevue
 */
public class FileUploadUtils {
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024L;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static final String DEFAULT_UPLOAD_PATH = ZonevueConfig.getUploadPath();


    private FileUploadUtils() {

    }
    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException io异常
     */
    public static String upload(final MultipartFile file) throws IOException {
        try {
            return upload(DEFAULT_UPLOAD_PATH, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (final Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException io异常
     */
    public static String upload(final String baseDir, final MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (final Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static String upload(final String baseDir, final MultipartFile file, final String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        final int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        final String fileName = extractFilename(file);

        final String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(final MultipartFile file) {
        return String.format("%s/%s_%s.%s", DateUtil.datePath(),
                FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.UPLOAD_SEQ_TYPE), getExtension(file));
    }

    public static File getAbsoluteFile(final String uploadDir, final String fileName) {
        final Path basePath = Paths.get(uploadDir);
        // normalize()方法会移除路径中的..和.等相对路径部分，以防止目录遍历
        final Path normalizedPath = basePath.resolve(uploadDir + File.separator + fileName).normalize();
        // 检查规范化后的路径是否以安全的基础路径开头
        if (normalizedPath.startsWith(basePath)) {
            final File desc = normalizedPath.toFile();

            if (!desc.exists() && !desc.getParentFile().exists() && !desc.getParentFile().mkdirs()) {
                // 目录创建失败
                throw new UtilException("文件创建失败：" + desc.getParentFile().getName());
            }
            return desc;
        } else {
            // 不以安全的基础路径开头
            throw new UtilException("非法的文件名：" + fileName);
        }
    }

    public static String getPathFileName(final String uploadDir, final String fileName) {
        final int dirLastIndex = ZonevueConfig.getProfile().length() + 1;
        final String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return Constants.RESOURCE_PREFIX + "/" + currentDir + fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException 异常
     */
    public static void assertAllowed(final MultipartFile file, final String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        final long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        final String fileName = file.getOriginalFilename();
        final String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
        {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
                throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension 输入mime类型
     * @param allowedExtensions 允许的类型数组
     * @return true/false
     */
    public static boolean isAllowedExtension(final String extension, final String[] allowedExtensions) {
        return Arrays.stream(allowedExtensions)
            .anyMatch(allowedExt -> allowedExt.equalsIgnoreCase(extension));
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(final MultipartFile file) {
        final String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            return MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
}
